import { getNearbyShopList } from "@src/api/shop";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import router from "@src/router";
import location from "@src/store/location";
const extConfig = wx.getExtConfigSync();

Component({
  options: {
    addGlobalClass: true
  },
  behaviors: [storeBindingsBehavior, router.routerBehavior],
  storeBindings: [{
    store: location,
    fields: ['latitude', 'longitude'],
    actions: ['getLocation', 'showAuthTip']
  }],
  properties: {
    title: {
      type: String,
      value: "参与门店"
    }
  },
  data: {
    visible: false,
    shopList: [],
    shopIds: [],
  },
  methods: {
    open(shopIds, list = []) {
      if (!shopIds) {
        shopIds = []
      };
      if (list.length > 0) {
        this.setData({ shopList: list, visible: true }); return;
      }
      this.setData({ shopIds: shopIds, shopList: [], visible: true });
      if (this.data.latitude == null || this.data.longitude === null) {
        this.getLocation().then((res) => {
          this.fetchData(res.latitude, res.longitude);
        }).catch(error => {
          this.fetchData();
        });
      } else {
        this.fetchData(this.data.latitude, this.data.longitude);
      }
    },
    handleClose() {
      this.setData({ visible: false })
    },
    handleStop() {
      return true;
    },
    callPhone(e) {
      console.log('e', e)
      let mobilePhone = e.currentTarget.dataset.item.mobilePhone;
      if (mobilePhone) {
        wx.makePhoneCall({
          phoneNumber: mobilePhone
        });
      }

    },
    //地图
    handleOpenMap(e) {
      let data = e.currentTarget.dataset.item
      wx.openLocation({
        latitude: data.latitude,
        longitude: data.longitude,
        name: data.name,
        address: data.address
      });
    },
    fetchData(latitude, longitude) {
      let params = {};
      if (latitude) {
        params.latitude = latitude;
        params.longitude = longitude;
      }
      params.idList = this.data.shopIds;
	  params.businessId = extConfig.businessId
      getNearbyShopList(params).then(res => {
        let list = res.data;
        list.forEach(item => {
          if (item.distance) {
            if (item.distance < 1000) {
              item.distance = item.distance.toFixed(2) + "米"
            } else {
              item.distance = (Math.round(item.distance / 100) / 10).toFixed(1) + "km"
            }
          }
        })
        this.setData({ shopList: list })
      });
    },
  }
});
